package cn.lzx.hrm.controller;

import cn.lzx.exctption.ValidUtil;
import cn.lzx.hrm.util.VerifyCodeUtils;
import cn.lzx.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/imageVerifyCode")
public class ImageVerifyCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取图片校验码
     * @param imageCodeKey
     * @return
     */
    @GetMapping("/{imageCodeKey}")
    public AjaxResult getImageCode (@PathVariable("imageCodeKey") String imageCodeKey){
        //断言 空值校验
        ValidUtil.assertNotNull(imageCodeKey,"系统错误");
        //产生验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //将验证码写入图片
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            VerifyCodeUtils.outputImage(150,50,data,code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //对图片进行base64编码
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encode = base64Encoder.encode(data.toByteArray());
        //吧验证码保存到ridex中
        redisTemplate.opsForValue().set(imageCodeKey,code,3, TimeUnit.MINUTES);
        //返回编码64的数据
        return AjaxResult.me().setResultObj(encode);
    }
    /**
     * 校验图片验证码
     */
    @PostMapping("/verify")
    public AjaxResult verify(@RequestBody Map<String,String>params){
        //空值校验
        ValidUtil.assertNotNull(params,"请输入图片验证码");
        //获取params中的key和code
        String key = params.get("imageCodeKey");
        String code = params.get("imageCode");
        //与rides中的key和code对比
        String redisCode = (String)redisTemplate.opsForValue().get(key);
        return redisCode.equalsIgnoreCase(code)?AjaxResult.me():AjaxResult.me().setSuccess(false).setMessage("验证码错误");
    }
}
